<template>
	<view class="container">
		<!-- <view class="tab" v-if="userType == 'STORE'||userType =='CAR'">
			<block v-for="(item, index) in tab" :key="index">
				<text :class="['', orderStatus == item.type ? 'on' : '' ]" @click="statusClick(item.type)"
					v-if="">{{item.name}}</text>
			</block>
		</view> -->
		<view class="tab" v-if="isSalesman">
			<block v-for="(item, index) in tabSale" :key="index">
				<text :class="['', orderStatus == item.type ? 'on' : '' ]" @click="statusClick(item.type)"
					v-if="">{{item.name}}</text>
			</block>
		</view>
		<view class="b" v-if="orderList.length > 0">
			<view class="uni-list" v-for="(item, index) in orderList" :key="index"
				@click="goOrderDetail(item.orderId, item.orderStatus)">
				<view class="uni-list-cell uni-list-cell-pd hd">
					<image mode="widthFix" :src="item.headImgUrl ||'../../../static/images/default_avatar.png'"></image>
					<!--{{userType == 'STORE'||userType =='CAR' ? item.saleStoreName : (item.orderUserName || item.orderPerson)}}-->
					<!-- <view v-if="userType == 'STORE'" class="uni-list-cell-db">
						<view class="h3">{{ item.saleStoreName }}</view>
					</view> -->
					<view v-if="isSalesman" class="uni-list-cell-db">
						<view class="h3">{{ item.orderUserName || item.orderPerson }}</view>
					</view>

					<text v-if="item.orderStatus == 'IN_PAY'">待支付</text>
					<text v-else-if="item.orderStatus == 'WAIT_PAY'">待支付</text>
					<text v-else-if="item.orderStatus == 'WAIT_SEND'">待发货</text>
					<text v-else-if="item.orderStatus == 'WAIT_RECEIVE'">待收货</text>
					<text v-else-if="item.orderStatus == 'FINISH'">已完成</text>
					<text v-else-if="item.orderStatus == 'CANCEL'">已取消</text>
				</view>
				<!-- <view class="uni-list-cell flex-row row-right plr-20">{{(item.createTime)}}</view> -->
				<!-- <view class="uni-list-cell uni-list-cell-pd bd" v-for="(itemn, indexn) in item.orderDetailDList"
					:key="index">
					<image mode="widthFix" :src="itemn.productImage" class="pic"></image>
					<view class="uni-list-cell-db">
						<view class="h3">{{itemn.productName}}</view>
						<view class="p uni-flex">
							<view class="uni-flex-item">￥{{itemn.orderPrice}}</view>
							<view>×{{itemn.detailNumber}}</view>
						</view>
					</view>
				</view> -->
				<view class="uni-list-cell uni-list-cell-pd">
					<view class="uni-list-cell-db">
						<!-- <view class="uni-inline-item">
							<view class="uni-flex-item">数量：</view>
							<view></view>
						</view> -->
						<view style="display: flex;color: #06A972;justify-content: space-between;">
							<view class="uni-flex-item">{{item.orderPerson}}</view>
							<view class="uni-flex-item">{{item.orderPhone}}</view>
						</view>
						<view style="display: flex;justify-content: space-between;">
							<view class="uni-flex-item">{{item.orderAddress}}</view>
							<view>
								<u-button type="success" @click.native.stop="openMapNavigation(item.orderAddress)"
									color="#06A972" size="small" text="导航" shape="circle"></u-button>
							</view>
						</view>
						<view>
							<view class="uni-flex-item">下单时间：{{(item.createTime)}}</view>
						</view>
						<view class="uni-inline-item">
							<view class="uni-flex-item">运费：</view>
							<view>￥{{item.freightPrice}}</view>
						</view>
						<view class="uni-flex">
							<view class="uni-flex-item">总价：</view>
							<text>￥{{item.totalPrice}}</text>
						</view>
						<!-- <view class="btn"
							v-if="(item.orderStatus == 'WAIT_PAY' || item.orderStatus == 'IN_PAY') && (userType == 'STORE'||userType =='CAR')">
							<view class="col-2">
								<u-button type="primary" @click.native.stop="cancelOrder(item.orderId)" text="取消订单"
									color="#f8f8f8" customStyle="color: #000;border: 1rpx solid #e6e6e6"></u-button>
							</view>
							<view class="col-2">
								<u-button type="primary" @click.native.stop="payment(item.orderId, item.totalPrice)"
									text="立即支付" color="#06A972"></u-button>
							</view>
						</view> -->
						<!-- <view class="btn btn-right"
							v-if="(userType == 'STORE'||userType =='CAR') && item.orderStatus == 'WAIT_RECEIVE'">
							<view class="col-2">
								<u-button type="primary" text="确认收货" @click.native.stop="receipt(item.orderId)"
									color="#06A972" customStyle="widht: 400rpx"></u-button>
							</view>
						</view> -->
						<view class="btn btn-right" v-if="isSalesman && item.orderStatus == 'WAIT_SEND'">
							<view class="col-2">
								<u-button type="primary" @click.native.stop="delivery(item.orderId)" text="发货"
									color="#06A972" customStyle="color: #fff;border: 1rpx solid #e6e6e6"></u-button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-else>
			<u-empty mode="favor" icon="../../../../static/images/comment.png" text="暂无内容" width="320" height="320"
				textSize="24"></u-empty>
		</view>
	</view>
</template>


<script>
	var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
	var qqmapsdk;
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from 'vuex';
	import {
		HEADER,
		HTTP_REQUEST_URL,
	} from '@/config/app';
	import {
		orderCancel,
		getMyOrderList,
		xcxPay,
		receipt,
		getSaleOrderList,
		delivery,
		amountPay,
		paySuccessPrint
	} from '@/api/order'
	import {
		getUserAmount
	} from '@/api/user.js'
	export default {
		data() {
			return {
				orderStatus: 0,
				page: 1,
				limit: 20,
				loading: false, //是否加载中
				loadend: false, //是否加载完毕
				loadTitle: '加载更多', //提示语
				orderList: [], //订单数组
				is_balance: true,
				userAmount: {},
				tab: [{
					name: '全部',
					type: 0
				}, {
					name: '待支付',
					// type: 'IN_PAY'
					type: 'WAIT_PAY'
				}, {
					name: '待发货',
					type: 'WAIT_SEND'
				}, {
					name: '待收货',
					type: 'WAIT_RECEIVE'
				}, {
					name: '订单完成',
					type: 'FINISH'
				}],
				tabSale: [{
					name: '全部',
					type: 0
				}, {
					name: '待支付',
					// type: 'IN_PAY'
					type: 'WAIT_PAY'
				}, {
					name: '待发货',
					type: 'WAIT_SEND'
				}, {
					name: '订单完成',
					type: 'FINISH'
				}],
			}

		},
		computed: mapGetters(['isLogin', 'uid', 'userType', 'isSalesman']),
		onLoad() {
			qqmapsdk = new QQMapWX({
				key: 'TNABZ-LWUCW-VT2RC-3XZY6-2N5LT-NIFGJ'
			});
		},
		onShow() {
			this.statusClick(0);
			if (this.isLogin) {
				this.page = 1;
				this.orderList = []
				this.loadend = false;
				this.getUserAmount();
			} else {
				toLogin();
			}
		},
		methods: {

			/**
			 * 切换类型
			 */
			statusClick: function(status) {
				//if (status == this.orderStatus) return;
				this.orderStatus = status;
				this.loadend = false;
				this.page = 1;
				this.$set(this, 'orderList', []);
				this.getOrderList();
			},

			/**
			 * 获取订单列表
			 */
			getOrderList() {
				let that = this;
				if (that.loadend) return;
				that.loading = true;
				that.loadTitle = '加载更多';
				let data = {
					userInfoId: that.uid,
					page: that.page,
					pageSize: that.limit,
				}
				if (that.orderStatus && that.orderStatus != 0) {
					data.orderStatus = that.orderStatus;
				}
				if (that.userType == 'STORE' && that.isSalesman) {
					getSaleOrderList(data)
						.then(res => {
							let list = res.value.list || [];
							let loadend = list.length < that.limit;
							list.forEach(e => {
					
							})
							that.orderList = that.$util.SplitArray(list, that.orderList);
							that.$set(that, 'orderList', that.orderList);
							that.loadend = loadend;
							that.loading = false;
							that.loadTitle = loadend ? '我也是有底线的' : '加载更多';
							that.page = that.page + 1;
						})
						.catch(err => {
							that.loading = false;
							that.loadTitle = '加载更多';
						});
				}
				else if (that.userType == 'STORE' || that.userType == 'CAR') {
					getMyOrderList(data)
						.then(res => {
							let list = res.value.list || [];
							let loadend = list.length < that.limit;
							list.forEach(e => {

							})
							that.orderList = that.$util.SplitArray(list, that.orderList);
							that.$set(that, 'orderList', that.orderList);
							that.loadend = loadend;
							that.loading = false;
							that.loadTitle = loadend ? '我也是有底线的' : '加载更多';
							that.page = that.page + 1;
						})
						.catch(err => {
							that.loading = false;
							that.loadTitle = '加载更多';
						});
				} else if (that.userType == 'SALE') {
					getSaleOrderList(data)
						.then(res => {
							let list = res.value.list || [];
							let loadend = list.length < that.limit;
							list.forEach(e => {

							})
							that.orderList = that.$util.SplitArray(list, that.orderList);
							that.$set(that, 'orderList', that.orderList);
							that.loadend = loadend;
							that.loading = false;
							that.loadTitle = loadend ? '我也是有底线的' : '加载更多';
							that.page = that.page + 1;
						})
						.catch(err => {
							that.loading = false;
							that.loadTitle = '加载更多';
						});
				}

			},

			/**
			 * 取消订单
			 */
			cancelOrder(orderId) {
				let that = this;
				uni.showModal({
					title: '取消订单',
					content: '是否取消订单',
					success: (res) => {
						if (res.confirm) {
							orderCancel({
								userInfoId: that.uid,
								orderId: orderId
							}).then(res => {
								that.$util.Tips({
									title: '取消订单成功'
								});
								that.orderList = [];
								that.loadend = false;
								that.page = 1;
								that.getOrderList();
							}).catch(err => {
								that.$util.Tips({
									title: err
								})
							});
						}
					}
				});
			},

			/**
			 * 确认收货
			 * @param {Object} orderId
			 */
			receipt(orderId) {
				let that = this;
				uni.showModal({
					title: '收货',
					content: '是否确认收货',
					success: (res) => {
						if (res.confirm) {
							receipt({
								userInfoId: that.uid,
								orderId: orderId
							}).then(res => {
								that.$util.Tips({
									title: '确认收货成功'
								});
								that.orderList = [];
								that.loadend = false;
								that.page = 1;
								that.getOrderList();
							}).catch(err => {
								that.$util.Tips({
									title: err
								})
							});
						}
					}
				});
			},

			/**
			 * 批发商发货
			 */
			delivery(orderId) {
				let that = this;
				uni.showModal({
					title: '发货',
					content: '是否确认发货',
					success: (res) => {
						if (res.confirm) {
							delivery({
								userInfoId: that.uid,
								orderId: orderId
							}).then(res => {
								that.$util.Tips({
									title: '发货成功'
								});
								that.orderList = [];
								that.loadend = false;
								that.page = 1;
								that.getOrderList();
							}).catch(err => {
								that.$util.Tips({
									title: err
								})
							});
						}
					}
				});
			},
			openMapNavigation(store) {
				// 调用正向地理编码接口
				qqmapsdk.geocoder({
					address: store, // 地址信息
					success(res) {
						// 获取经纬度信息
						uni.openLocation({
							latitude: parseFloat(res.result.location.lat), // 纬度
							longitude: parseFloat(res.result.location.lng), // 经度
							name: store.userName, // 门店名称
							address: store, // 详细地址
							success() {
								console.log("导航成功");
							},
							fail(err) {
								console.error("导航失败", err);
								uni.showToast({
									title: '导航失败，请检查位置权限',
									icon: 'none'
								});
							}
						});
					},
					fail(err) {
						// 失败回调
						console.error(err);
					}
				})
			},

			/**
			 * 立即支付
			 */
			payment(orderId, totalPrice) {
				let that = this;
				uni.showModal({
					title: '支付',
					content: '是否支付',
					success: (res) => {
						if (res.confirm) {
							// if (that.is_balance) {
							// 	console.log(that.userAmount.totalPrice , totalPrice);
							// 	if (that.userAmount.totalPrice < totalPrice) {
							// 		uni.hideLoading();
							// 		return that.$util.Tips({
							// 			title: '余额不足，请前去充值',
							// 		}, {
							// 			tab: 5,
							// 			url: '/pages/users/user_payment/index'
							// 		});
							// 	} else {
							// 		that.amountPay(orderId);
							// 	}
							// } else {
							xcxPay({
								orderId: orderId,
								userInfoId: that.uid
							}).then(res => {
								let goPages = '/pages/goods/order_pay_status/index';
								goPages += '?orderId=' + orderId;
								let jsConfig = res.value.param;
								// #ifdef MP
								uni.requestPayment({
									timeStamp: jsConfig.timeStamp,
									nonceStr: jsConfig.nonceStr,
									package: jsConfig.package,
									signType: jsConfig.signType,
									paySign: jsConfig.paySign,
									success: function(res) {
										uni.hideLoading();
										paySuccessPrint({
											orderId: orderId,
										}).then(res => {

										})
										return that.$util.Tips({
											title: '支付成功',
											icon: 'success'
										}, {
											tab: 5,
											url: goPages + '&status=1'
										});
									},
									fail: function(e) {
										console.log("取消支付");
										// 调用后端接口，更新订单状态为待支付
										uni.request({
											url: HTTP_REQUEST_URL +
												'/api/order/cancelPayment',
											// url: HTTP_REQUEST_URL + '/order/cancelPayment',
											method: 'POST',
											data: {
												orderId: orderId
											},
											success: () => {
												console.log(
													'订单状态更新为待支付'
												);
											},
										});
										uni.hideLoading();
										return that.$util.Tips({
											title: '取消支付'
										}, {
											tab: 5,
											url: goPages + '&status=2'
										});
									},
									complete: function(e) {
										uni.hideLoading();
										//关闭当前页面跳转至订单状态
										if (res.errMsg ==
											'requestPayment:cancel')
											return that.$util
												.Tips({
													title: '取消支付'
												}, {
													tab: 5,
													url: goPages +
														'&status=2'
												});
									},
								})
								// #endif
							}).catch(err => {
								that.$util.Tips({
									title: err.msg
								});
							});
							// }

						}
					}
				});

			},

			goOrderDetail(orderId) {
				this.$util.Tips('/pages/goods/order_detail/index?orderId=' + orderId);
			},

			/* 余额支付
			 * @param {Object} orderId
			 */
			amountPay(orderId) {
				console.log(orderId);
				let that = this;
				amountPay({
					userInfoId: that.uid,
					orderId: orderId
				}).then(res => {
					uni.hideLoading();
					let goPages = '/pages/goods/order_pay_status/index';
					goPages += '?orderId=' + orderId;
					return that.$util.Tips({
						title: '支付成功',
						icon: 'success'
					}, {
						tab: 5,
						url: goPages + '&status=1'
					});
				}).catch(err => {
					uni.hideLoading();
					that.$util.Tips({
						title: err.msg
					});
				})
			},

			/**
			 * 获取余额
			 */
			getUserAmount() {
				let that = this;
				getUserAmount({
					userInfoId: that.uid
				}).then(res => {
					that.userAmount = res.value;
				})
			},

		},

		onReachBottom: function() {
			this.getOrderList();
		}
	}
</script>

<style>
	page {

		background: #F8F8F8;
	}

	.container .tab {
		display: flex;
		align-items: center;
		text-align: center;
		background: #fff;
	}

	.container .tab text {
		padding: 20rpx 0;
		position: relative;
		margin-left: 40rpx;
	}

	.container .tab .on {
		font-weight: bold;
		font-size: 36rpx;
		color: #06A972;
	}

	.container .tab .on::after {
		content: '';
		width: 72rpx;
		height: 4rpx;
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translate(-50%, 0);
		background: #06A972;
		border-radius: 2px 2px 2px 2px;
	}

	.container .b {
		padding: 20rpx;
	}

	.container .b .uni-list {
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}

	.container .b .hd text {
		color: #06A972;
	}

	.container .b .hd image {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}

	.container .b .pic {
		width: 148rpx;
		height: 168rpx;
		margin-right: 20rpx;
	}

	.container .b .h3 {
		line-height: 40rpx;
		font-weight: bold;
	}

	.container .b .bd .h3 {
		margin-bottom: 15rpx;
	}

	.container .b .p .uni-flex-item {
		font-size: 32rpx;
		font-weight: bold;
		color: #E91E1E;
	}

	.container .b .uni-inline-item {
		color: #BDBDBD;
	}

	.container .b .uni-flex text {
		font-size: 32rpx;
		font-weight: bold;
	}

	.container .b .btn {
		margin-top: 15rpx;
		display: flex;
		justify-content: space-between;
	}

	.container .b .btn-right {
		margin-top: 15rpx;
		display: flex;
		justify-content: flex-end;
	}

	.col-2 {
		width: 48%;
	}

	.container .b .btn button {
		font-size: 28rpx;
		border-radius: 60rpx;
	}

	.plr-20 {
		padding: 0 30rpx;
	}
</style>